package heap.hard;

import java.util.PriorityQueue;

/**
 * 合并K个升序链表
 * 示例 1：
 * 输入：lists = [[1,4,5],[1,3,4],[2,6]]
 * 输出：[1,1,2,3,4,4,5,6]
 * 解释：链表数组如下：
 * [
 *   1->4->5,
 *   1->3->4,
 *   2->6
 * ]
 * 将它们合并到一个有序链表中得到。
 * 1->1->2->3->4->4->5->6
 * 示例 2：
 *
 * 输入：lists = []
 * 输出：[]
 * 示例 3：
 *
 * 输入：lists = [[]]
 * 输出：[]
 * 链接：https://leetcode-cn.com/problems/merge-k-sorted-lists
 */
public class MergeKSortedLists_23 {

    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> heap = new PriorityQueue<>((l1, l2) -> l1.val - l2.val);
        for (ListNode list : lists){
            if (list != null)
                heap.offer(list);
        }
        ListNode res = new ListNode(0), cur = res;
        while(!heap.isEmpty()) {
            ListNode poll = heap.poll();
            cur.next = poll;
            cur = cur.next;
            if(poll.next != null)
                heap.offer(poll.next);
        }
        return res.next;
    }

    public static void main(String[] args) {
        MergeKSortedLists_23 mk = new MergeKSortedLists_23();
        ListNode[] lists = new ListNode[]{new ListNode(0), new ListNode(1), new ListNode(2)};

        mk.mergeKLists(lists);
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}